/*
 *	Page Scroller - jQuery Plugin (minified)
 *	Simple plugin to create a smooth scrolling page with updating links
 *  download by http://www.codefans.net
 *	Support at: http://dairien.com
 *
 *	Copyright (c) 2012 Dairien Boyd. All Rights Reserved
 *
 *	Version: BETA - IE Still Unsupported (2/2/2012)
 *	Requires: jQuery v1.3+
 *
 *	This library is released under the BSD license:
 *
 *	Redistribution and use in source and binary forms, with or without
 *	modification, are permitted provided that the following conditions are met:
 *
 *	Redistributions of source code must retain the above copyright notice, this
 *	list of conditions and the following disclaimer. Redistributions in binary
 *	form must reproduce the above copyright notice, this list of conditions and
 *	the following disclaimer in the documentation and/or other materials
 *	provided with the distribution. Neither the name Dairirien Boyd nor
 *	the names of its contributors may be used to endorse or promote products
 *	derived from this software without specific prior written permission.
 *	ÀÁÈËÖ®¼Ò  lanrenzhijia.com
 *	THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 *	AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 *	IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 *	ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR
 *	ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 *	DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
 *	SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
 *	CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 *	LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
 *	OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
 *	DAMAGE.
 */
var pageScroller = {};
(function ($) {
    $.fn.extend({
        pageScroller: function (opts) {
            opts = $.extend({
                currentSection: 0
                , sectionClass: "section"
                , navigationClass: "scrollNav"
                , animationSpeed: 500
                , scrollOffset: 20
                , navigation: []
                , animationBefore: function () {}
                , animationComplete: function () {}
                , onChange: function () {}
            }, opts);
            var pageScroll = function (dom, _opts) {
                $.fx.interval = 5;
                dom.append('<ul class="pageScroll"></ul>');
                pageScroller.navi = $(".pageScroll", dom);
                pageScroller.navi.addClass("left");
                pageScroller.sections = $("." + _opts.sectionClass, dom);
                pageScroller.scrollDocument = $(document);
                pageScroller.scrollWindow = $(window);
                pageScroller.scrollBody = $("body");
                pageScroller.scrollPosition = pageScroller.scrollWindow.scrollTop();
                pageScroller.currentSection = pageScroller.scrollWindow.height();
                pageScroller.options = _opts;
                dom.css({position: "relative"});
                pageScroller.sections.each(function (i) {
                    var section = $(this);
                    section.css({
                        position: "relative"
                        , margin: 0
                    })
                        .addClass(pageScroller.options.sectionClass + "_" + (i + 1));
                    var sectionStr='<li class="' + _opts.navigationClass + " " + _opts.navigationClass + "_" + (i + 1) + '">';
                    sectionStr+= '<a href="#pageScroll' + i + '">';
                    sectionStr+= pageScroller.options.navigation.length ? pageScroller.options.navigation[i] : ('Navigation ' + (i + 1));
                    sectionStr+= '</a></li>';
                    pageScroller.navi.append(sectionStr);
                });
                pageScroller.pageLinks = $("li", pageScroller.navi);
                pageScroller.pageLinks.each(function (i) {
                    $("a", this).click(function (ev) {
                        ev.preventDefault();
                        _opts.animationBefore();
                        updateSection(pageScroller.sections.eq(i), i);
                    })
                });
                pageScroller.next = function () {
                    var nexti = pageScroller.options.currentSection + 1;
                    if (nexti != pageScroller.sections.length) {
                        updateSection(pageScroller.sections.eq(nexti), nexti);
                    }
                };
                pageScroller.prev = function () {
                    var previ = pageScroller.options.currentSection - 1;
                    0 >= previ && (previ = 0);
                    updateSection(pageScroller.sections.eq(previ), previ);
                };
                /**
                 * 切换到第 i（从 1 开始） 项
                 * @param i
                 */
                pageScroller.goTo = function (i) {
                    i--;
                    updateSection(pageScroller.sections.eq(i), i);
                };
                pageScroller.scrollWindow.scroll(scrollHandler);
                setTimeout(function () {
                    // 初始化时若在顶部，不会触发 pageScroller.scrollWindow.scroll 事件，需手动触发一次
                    0 == pageScroller.scrollPosition && scrollHandler();
                }, 200)
            };
            /**
             * 滚动监听，根据 section 的状态修改导航栏状态
             */
            var scrollHandler = function () {
                pageScroller.scrollPosition = pageScroller.scrollWindow.scrollTop();
                pageScroller.scrollDistance = pageScroller.scrollPosition + pageScroller.currentSection;
                for (var i = 0; i < pageScroller.sections.length; i++) {
                    var secOffset = pageScroller.sections.eq(i).offset().top;
                    pageScroller.options.scrollOffset && (secOffset -= pageScroller.options.scrollOffset);
                    var nextSecOffset = 0;
                    if (i < pageScroller.sections.length - 1){
                        nextSecOffset = pageScroller.sections.eq(i + 1).offset().top - (pageScroller.options.scrollOffset || 0);
                        var b = pageScroller.pageLinks.eq(i);
                        var c = pageScroller.pageLinks.eq(pageScroller.sections.length - 1);
                    }
                    if (pageScroller.scrollBody.is(":animated")) return !1;
                    if (pageScroller.scrollDocument.height() == pageScroller.scrollDistance) {
                        if (!c.hasClass("active")){
                            updateLink(pageScroller.sections.length - 1);
                            return !1;
                        }
                    } else if (nextSecOffset) {
                        if (pageScroller.scrollPosition >= secOffset && pageScroller.scrollPosition < nextSecOffset && !b.hasClass("active")){
                            updateLink(i);
                            return !1
                        }
                    } else if (pageScroller.scrollPosition >= secOffset && i == pageScroller.sections.length - 1 && !pageScroller.pageLinks.eq(pageScroller.sections.length - 1).hasClass("active")){
                        updateLink(pageScroller.sections.length - 1);
                        return !1;
                    }
                }
            };
            /**
             * 将指定的 section 移入视图
             * @param section {object} section 对应的 jquery 元素
             * @param i {number} section 对应的索引
             */
            var updateSection = function (section, i) {
                var offset = section.offset().top;
                pageScroller.options.scrollOffset && (offset -= pageScroller.options.scrollOffset);
                var body = $("html, body"), f = $(window).scrollTop();
                offset != f && !body.is(":animated") && body.animate({scrollTop: offset}, pageScroller.options.animationSpeed, function () {
                    updateLink(i);
                    pageScroller.options.animationComplete();
                })
            };
            /**
             * 修改导航栏状态
             * @param i {number} 当前选中的 pageLink 对应的索引
             */
            var updateLink = function (i) {
                pageScroller.pageLinks.removeClass("active");
                pageScroller.pageLinks.eq(i).addClass("active");
                pageScroller.options.currentSection = i;
                pageScroller.options.onChange();
            };
            // 未进行过 index
            if (!pageScroller.options) return pageScroll(this, opts);
        }});
})(jQuery);